package cn.emall.content.service.impl;

import cn.emall.content.service.ContentService;
import cn.emall.jedis.JedisClient;
import cn.emall.mapper.TbContentMapper;
import cn.emall.pojo.*;
import cn.emall.utils.EmallResult;
import cn.emall.utils.JsonUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 内容管理Service
 */
@Service
public class ContentServiceImpl implements ContentService {

    @Autowired
    private TbContentMapper tbContentMapper;
    @Value("${CONTENT_LIST}")
    private String CONTENT_LIST;
    @Autowired
    private JedisClient jedisClient;

    /**
     * 添加内容
     * @param tbContent
     * @return
     */
    @Override
    public EmallResult addContent(TbContent tbContent) {
        //将内容插入到内容表
        tbContent.setCreated(new Date());
        tbContent.setUpdated(new Date());
        tbContentMapper.insert(tbContent);
        //缓存同步,删除缓存中对应的数据
        jedisClient.hdel(CONTENT_LIST,tbContent.getCategoryId().toString());
        return EmallResult.ok(tbContent);
    }

    /**
     * 根据内容分类id查询内容
     * @param cid
     * @return
     */
    @Override
    public List<TbContent> getContentListByCid(Long cid) {
        //查询缓存
        try {
            //如果缓存中有直接响应缓存结果
            String json = jedisClient.hget(CONTENT_LIST,cid + "");
            if(StringUtils.isNotBlank(json)){
                List<TbContent> list = JsonUtils.jsonToList(json,TbContent.class);
                return list;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        //缓存中如果没有则查询数据库
        TbContentExample example = new TbContentExample();
        TbContentExample.Criteria criteria = example.createCriteria();
        criteria.andCategoryIdEqualTo(cid);
        //执行查询
        List<TbContent> ad1List = tbContentMapper.selectByExampleWithBLOBs(example);
        //把结果添加到缓存中
        try{
            jedisClient.hset(CONTENT_LIST,cid + "",JsonUtils.objectToJson(ad1List));
        }catch (Exception e){
            e.printStackTrace();
        }
        return ad1List;
    }
}
